package erp_services

import (
	"errors"
	"xiehui-service/app/models/erp_models"
	"xiehui-service/global"
)

type materialDayConsumptionService struct {
}

type SearchDayCondtion struct {
	SubcompanyId     string
	MixerNo          string
	StatDay          string
	Material         string
	ConcreteCategory string
}

var MaterialDayConsumptionService = new(materialDayConsumptionService)

// 获取单条信息
func (materialDayConsumptionService *materialDayConsumptionService) GetOneInfo(id uint) (pMDC *erp_models.MaterialDayConsumption, err error) {
	err = global.App.DB.First(&pMDC, id).Error
	if err != nil {
		pMDC = nil
		if err.Error() == "record not found" {
			err = errors.New("数据不存在")
		}
	}
	return
}

// 判断数据是否存在
func (materialDayConsumptionService *materialDayConsumptionService) GetByDay(sCond SearchDayCondtion) (pMDC *erp_models.MaterialDayConsumption, err error) {
	err = global.App.DB.Where("station_id = ? AND mixer_no = ? AND material = ? AND stat_day = ? AND concrete_category = ? ", sCond.SubcompanyId, sCond.MixerNo, sCond.Material, sCond.StatDay, sCond.ConcreteCategory).First(&pMDC).Error
	if err != nil {
		pMDC = nil
		if err.Error() == "record not found" {
			err = errors.New("数据不存在")
		}
	}
	return
}

// 新增信息
func (materialDayConsumptionService *materialDayConsumptionService) Create(mDC *erp_models.MaterialDayConsumption) (uint, error) {
	result := global.App.DB.Create(&mDC)
	if result.Error != nil {
		return 0, result.Error
	}
	return mDC.ID.ID, nil
}

func (materialDayConsumptionService *materialDayConsumptionService) Update(mDC erp_models.MaterialDayConsumption) (err error) {
	if err := global.App.DB.Model(&erp_models.MaterialDayConsumption{}).Where("ID = ?", mDC.ID.ID).Omit("ID", "UnionNo", "SubcompanyId", "CreatedBy", "CreatedAt").Updates(&mDC).Error; err != nil {
		return err
	}
	return nil
}

// 根据ID更新数据
func (materialDayConsumptionService *materialDayConsumptionService) SetById(id uint, fields map[string]interface{}) (err error) {
	var mDC erp_models.MaterialDayConsumption
	if err = global.App.DB.First(&mDC, id).Error; err != nil {
		err = errors.New("未查询到信息")
		return
	}

	if err = global.App.DB.Model(&mDC).Updates(fields).Error; err != nil {
		return
	}

	return nil
}
